/**
 * 版本信息表单页面
 * wangmei
 */

import React from 'react';
import { Form, Input, Button, Row, Col, message, Select } from 'antd';
import BreadcrumbCustom from '../BreadcrumbCustom';
import ModalPage from './VersioninfoMangerModal';
import * as Request from '../../Server/Upgrade';
import * as Const from '../../common/const';
import qs from 'qs';

const FormItem = Form.Item;
const Option = Select.Option;

class VersioninfoMangerForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            show: false, //选用模板显示隐藏状态
            rows: {} //单条记录信息
        };
    }

    componentWillMount() {
        const { params } = this.props.match;
        if (params.id != " ") {
            //通过id查询单条记录信息的方法
            const _param = qs.stringify({ id: params.id })
            Request.getVersionInfoById(_param).then(res => {
                if (res && res.code == Const.REQUEST_SUCCESS) {
                    this.setState({
                        rows: res.data
                    })
                } else {
                    res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg, Const.ERROR_DISAPPEAR_TIME);
                }
            });
        }
    }
    
    isObjEqual = (o1,o2) =>{
        let props1 = Object.getOwnPropertyNames(o1);
        let props2 = Object.getOwnPropertyNames(o2);
        if (props1.length != props2.length) {
            return false;
        }
        for (let i = 0,max = props1.length; i < max; i++) {
            let propName = props1[i];
            if (o1[propName] !== o2[propName]) {
                return false;
            }
        }
        return true;
    }
    
    //保存方法
    handleSubmit = (e) => {
        e.preventDefault();
        const { rows } = this.state;
        const { params } = this.props.match;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                if (params.id == " ") { //新增
                    values.templateId = rows.id ? rows.id : 0;
                    values.svrRoot = values.svrRoot.replace(/\s*/g,"");
                    values.downdir = values.downdir.replace(/\s*/g,"");
                    const _param = qs.stringify(values);
                    Request.versionInfoSave(_param).then(res => {
                        if (res && res.code == Const.REQUEST_SUCCESS) {
                            message.success('添加成功', Const.AUTO_DISAPPEAR_TIME);
                            this.setState({
                                rows: {}
                            })
                            this.props.history.push('/app/upgrade/version');
                        } else {
                            res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg);
                        }
                    })
                } else { // 修改
                    values.id = rows.id;
                    let equalState = !(values.clientversion==rows.clientversion)||!(values.vertype==rows.vertype)
                    const _param = qs.stringify(values);
                    Request.versionInfoUpdate(_param).then(res => {
                        if (res && res.code == Const.REQUEST_SUCCESS) {
                            if(rows.tag==1&&equalState){
                                const param = {
                                    tag: 0,
                                    id: values.id
                                };
                                const _param = qs.stringify(param);
                                Request.versionInfoUpdateTag(_param).then(res=>{
                                    if (res && res.code == Const.REQUEST_SUCCESS) {
                                        message.success('修改成功', Const.AUTO_DISAPPEAR_TIME);
                                        this.setState({
                                            rows: {}
                                        })
                                        this.props.history.push('/app/upgrade/version');
                                    } else {
                                        res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg, Const.ERROR_DISAPPEAR_TIME);
                                    }
                                });
                            }else{
                                message.success('修改成功', Const.AUTO_DISAPPEAR_TIME);
                                this.setState({
                                    rows: {}
                                })
                                this.props.history.push('/app/upgrade/version');
                            }
                        } else {
                            res && res.code !== Const.REQUEST_UNAUTHORIZED && message.error(res.msg);
                        }
                    })
                }
            }
        });
    }

    //显示或者隐藏方法
    showModalFunc = (flag, rows) => {
        this.setState({
            show: flag,
            rows: rows
        })
    }

    validateClientVersion = (rule, value, callback) => {
        if (value == '' || value == undefined) {
            callback("请输入客户端版本");
            return;
        } else if (!this.checkVersions(value)) {
            callback("客户端版本输入不合法");
            return;
        }
        callback();
    }

    validatePatchVersion = (rule, value, callback) => {
        const reg = /^\d+\.\d+\.\d+\.\d+$/;
        if (value == '' || value == undefined) {
            callback("请输入升级后版本");
            return;
        } else if (!reg.test(value)) {
            callback("升级版本输入不合法");
            return;
        }
        callback();
    }

    //校验版本号
    checkVersions = (versions) => {
        if (versions == null) {
            return false;
        }

        const vers = versions.split(';');
        for (let i = 0; i < vers.length; i++) {
            if (!vers[i].match(/^((\d+)|x)\.((\d+)|x)\.((\d+)|x)\.((\d+)|x)$/)) {
                return false;
            }
        }
        return true;
    }

    backClick = () =>{
        this.props.history.push('/app/upgrade/version');
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        const { params } = this.props.match;
        const { show, rows } = this.state;
        const title = params.id != " " ? "修改信息" : "新增信息";
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 13 },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 16,
                    offset: 11,
                },
            },
        };

        return (
            <div>
                <BreadcrumbCustom first={title} />
                {show && <ModalPage showModalFunc={this.showModalFunc} />}
                <Form onSubmit={this.handleSubmit}>
                    <FormItem
                        {...formItemLayout}
                        label="默认下载地址"
                    >
                        {getFieldDecorator('svrRoot', {
                            rules: [{
                                required: true,
                                message: '请输入默认下载地址！'
                            }],
                            initialValue: rows.svrRoot
                        })(
                            <Input maxLength={250} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="客户端版本"
                    >
                        {getFieldDecorator('clientversion', {
                            rules: [{
                                required: true,
                                validator: this.validateClientVersion,
                            }],
                            initialValue: rows.clientversion
                        })(
                            <Input maxLength={250} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="升级后版本"
                    >
                        {getFieldDecorator('patchversion', {
                            rules: [{
                                required: true,
                                validator: this.validatePatchVersion
                            }],
                            initialValue: rows.patchversion
                        })(
                            <Input maxLength={250} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={'下载到本地路径'}
                    >
                        {getFieldDecorator('downdir', {
                            rules: [{ 
                                required: true, 
                                message: '请输入下载到本地路径！' 
                            }],
                            initialValue: rows.downdir
                        })(
                            <Input maxLength={250} />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={'版本类型'}
                    >
                        {getFieldDecorator('vertype', {
                            initialValue: rows.vertype?rows.vertype:'Pro'
                        })(
                            <Select>
                                {Const.VERTYPE.map((item, index) => {
                                    return <Option value={item.value}>{item.title}</Option>
                                })}
                            </Select>
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="备注"
                    >
                        {getFieldDecorator('remark', {
                            initialValue: rows.remark
                        })(
                            <Input maxLength={255} type="textarea" rows={3} placeholder="备注，250个字以内" />
                        )}
                    </FormItem>
                    {params.id == " "&&<Row>
                        <Col span={3} offset={18}>
                            <label onClick={() => this.showModalFunc(true, {})} style={{ textDecoration: "underline", marginLeft: '-3%',cursor:'pointer' }}>选用模板</label>
                        </Col>
                    </Row>}
                    <FormItem {...tailFormItemLayout}>
                        <Button type="primary" htmlType="submit" >保存</Button>
                        <Button type="primary" onClick={this.backClick}>
                            返回
                        </Button>
                    </FormItem>
                </Form>
            </div>
        );
    }
}

const WrappedVersioninfoMangerForm = Form.create()(VersioninfoMangerForm);

export default WrappedVersioninfoMangerForm;